package com.hy.logtrace.domain;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hy.logtrace.util.TraceIdContext;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class TraceWrapper extends HashMap<String, Object> {

    private static final HashMap<String, Method> methodCache = new HashMap<>();

    private final ObjectMapper objectMapper;

    // 构造函数注入 ObjectMapper
    public TraceWrapper(ObjectMapper objectMapper) {
        super();
        this.objectMapper = objectMapper;
        super.put(TraceIdContext.getTraceKey(), TraceIdContext.getTraceId());
    }

    public void wrapObject(Object obj) {
        if (obj == null) {
            return;
        }

        try {
            // 使用注入的 ObjectMapper 将对象转换为 Map
            Map<String, Object> objectAsMap = objectMapper.convertValue(obj, new TypeReference<Map<String, Object>>() {});

            // 将 Map 中的所有键值对存入 TraceWrapper
            this.putAll(objectAsMap);
        } catch (Exception e) {
            throw new RuntimeException("[TraceWrapper.wrapObject]: Failed to convert object to map", e);
        }
    }
}
